import "../styles/style.css";
import CsvDownloader from "react-csv-downloader";
import axios, { AxiosResponse } from "axios";
import { registerables } from "chart.js";
import React, { useState } from 'react'
import { CSVLink } from "react-csv";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Doughnut } from 'react-chartjs-2';

ChartJS.register(ArcElement, Tooltip, Legend);

const colors =  [
  'rgb(255, 206, 86)',
  'rgb(75, 192, 192)',
  'rgb(122, 220, 25)',
  'rgb(11, 243, 178)',
  'rgb(150, 232, 121)',
  'rgb(33, 58, 145)',
  'rgb(157, 171, 202)',
  'rgb(205, 93, 155)',
  'rgb(153, 225, 49)',
  'rgb(245, 150, 76)',
  'rgb(131, 125, 125)',
  'rgb(219, 241, 35)'
]

const add_category = (category_name)=>{
  axios({
    method: 'post',
    url: '/api/transactions/categories/add',
    data: {
      name: category_name
    }
  }).then(function (response) {
    console.log(response)
    
  }).catch(error => {
    alert(error.response.data.detail)
 })};


export const CustomDropdown = (props) => (
  <div>
    <strong>{props.username}</strong>
    <select
      className="form-control"
      name="{props.name}"
      onChange={props.onChange}
    >
      <option>Select {props.name}</option>
      {props.options.map((item, index) => (
        <option key={index} value={item.id}>
          {item.name}
        </option>
      ))}
    </select>
  </div>
)

const logout = () =>{
  document.cookie = "";
  window.location.replace("/login");
}

function forecast(data, days = 1) {
  console.log(data)
  if (Array.isArray(data)) {
    if (data.length > 0) {
      let s = 0;
      let c = data.length;
      data.forEach((it) => (s += it));
      let avg = s / c;
      return (
        "Estimated spending for the " + days + " day: " + avg * days + "P"
      );
    } else {
      return "Not enough data to predict";
    }
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.download = this.download.bind(this);
    this.amountHandler =  this.amountHandler.bind(this)
    this.new_categoryHandler = this.new_categoryHandler.bind(this)
    this.productHandler = this.productHandler.bind(this)
    this.submitWaste = this.submitWaste.bind(this)
    this.categoryHandler = this.categoryHandler.bind(this)

    this.state = {
      amount:"",
      category:"",
      new_category:"",
      product:"",
      dataToDownload: [],
      collection: [],
      value: '',
      chart_today: {labels: [], // категории // сюда воткнуть норм категории перед презентацией проекта
      datasets: [
        {
          label: '',
          data: [12, 19, 3, 5, 2, 3, 1, 2, 6, 11], // траты по категориям за день // сюда воткнуть норм значения перед презентацией проекта
          backgroundColor: [
            'rgb(255, 206, 86)',
            'rgb(75, 192, 192)',
            'rgb(122, 220, 25)',
            'rgb(11, 243, 178)',
            'rgb(150, 232, 121)',
            'rgb(33, 58, 145)',
            'rgb(157, 171, 202)',
            'rgb(205, 93, 155)',
            'rgb(153, 225, 49)',
            'rgb(245, 150, 76)',
            'rgb(131, 125, 125)',
            'rgb(219, 241, 35)'
          ],
          borderWidth: 1,
        },
      ]},
      chart_month:{labels: [], // категории // сюда воткнуть норм категории перед презентацией проекта
      datasets: [
        {
          label: '',
          data: [12, 19, 3, 5, 2, 3, 1, 2, 6, 11], // траты по категориям за день // сюда воткнуть норм значения перед презентацией проекта
          backgroundColor: [
            'rgb(255, 206, 86)',
            'rgb(75, 192, 192)',
            'rgb(122, 220, 25)',
            'rgb(11, 243, 178)',
            'rgb(150, 232, 121)',
            'rgb(33, 58, 145)',
            'rgb(157, 171, 202)',
            'rgb(205, 93, 155)',
            'rgb(153, 225, 49)',
            'rgb(245, 150, 76)',
            'rgb(131, 125, 125)',
            'rgb(219, 241, 35)'
          ],
          borderWidth: 1,
        },
      ]}
  }
}


componentDidMount() {
  fetch('http://localhost/api/transactions/categories/all')
  .then((response) => response.json())
  .then((res) => {this.setState({ collection: res })
  var data_to_download = [];
  const token_val = document.cookie.replace(
    /(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/,
    "$1"
  );
  axios({
    method: "post",
    url: "/api/transactions/get_all_transactions",
    data: {
          token: token_val
        }
  }).then((response)=>{
    data_to_download=response.data
    this.setState({ dataToDownload: data_to_download });
    //after reqs
    let category_names =[]
    let category_with_ids = this.state.collection
    let today_trs_per_categ=[]
    let month_trs_per_categ=[]
    category_with_ids.forEach(it=>category_names.push(it.name))
    let cid=[]
    category_with_ids.forEach(
      it2=>{
        let key = ((it2.id).toString())
        cid[key]=it2.name
      }
    )
    let temp_d = []
    let temp_m = []
    let date = new Date()
    let month = date.getMonth()
    let day = date.getDate()
    console.log(day)
    console.log(month)
    category_names.forEach(it1=>temp_d[it1]=0)
    category_names.forEach(it1=>temp_m[it1]=0)

    this.state.dataToDownload.forEach(it=>{
      
      var d = new Date(it.timestamp)
      console.log(it)
      console.log(d)
      console.log(d.getDate())
      if(d.getDate()===day){
        temp_d[cid[it.category_id]]+=it.cost
      }
      if(d.getMonth()===month){
        temp_m[cid[it.category_id]]+=it.cost
      }
    })
    console.log(temp_d)
    let final_dd = []
    let final_md = []
    category_names.forEach(it=>final_dd.push(temp_d[it]))
    category_names.forEach(it=>final_md.push(temp_m[it]))



  let data_today = {
    labels: category_names,
    datasets:[{
      label: '',
      data: final_dd,
      backgroundColor: colors,
      borderWidth: 1
    }
    ]
  }
  let data_month = {
    labels: category_names,
    datasets:[{
      label: '',
      data: final_md,
      backgroundColor: colors,
      borderWidth: 1
    }
    ]
  }
  this.setState({chart_today: data_today})
  this.setState({chart_month: data_month})


  })
  
})

}

  submitWaste(){
    const token_val = document.cookie.replace(
      /(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/,
      "$1"
    );
    var amo = document.getElementById("amount").value
    var prod = document.getElementById("product").value
    var categ=this.state.category
    axios({
      method: "post",
      url: "/api/transactions/add",
      data: {
            name: prod,
            cost: amo,
            category_id: categ,
            token: token_val
          }
    }).then((response)=>{
      alert(response.data)
    })
  }
  amountHandler(event){
    this.setState({amount: event.target.value})
  }
  new_categoryHandler(event){
    this.setState({new_category: event.target.value})
  }
  productHandler(event){
    this.setState({product: event.target.value})
  }
  categoryHandler(event){
    this.setState({category: event.target.value})
  }

  download(event) {
    const token_val = document.cookie.replace(
      /(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/,
      "$1"
    );
      var data_to_download = [];
      axios({
        method: "post",
        url: "/api/transactions/get_all_transactions",
        data: {
              token: token_val
            }
      }).then((response)=>{
        data_to_download=response.data
        this.setState({ dataToDownload: data_to_download }, () => {
          this.csvLink.link.click();
        });
      })
    }

    

  render(){
  return (
    <div className="App">
      <div style={{position: "fixed", top: "30px", left: "575px"}}>
        <CustomDropdown id="category_select"
          name={this.state.name}
          options={this.state.collection}
          onChange={this.categoryHandler}
        />
      </div>

      {/* обе диаграммы, возможно придется менять еще че то (TODO) */}
      <div style={{position: "fixed", top: "150px", left: "700px", height: "400px", width: "750px", backgroundColor: "#FFF", borderRadius: "50px", borderWidth: "0px"}}>
        <div style={{position:"fixed", top: "200px", left: "750px", height: "350px", width: "300px", textAlign: "center"}}>
          <Doughnut style={{objectFit: "contain"}} data={this.state.chart_today} />
          Expenses today
        </div>
        <div style={{position:"fixed", top: "200px", left: "1100px", height: "350px", width: "300px", textAlign: "center"}}>
          <Doughnut style={{objectFit: "contain"}} data={this.state.chart_month} />
          Expenses this month
        </div>
      </div>
      <button style={{ position: "fixed", top: 340, left: 25, borderRadius: 50, borderWidth: 0, padding: "15px", backgroundColor: "#FFF"}} onClick={this.download}>Download .csv</button>
      <div>
          <CSVLink
            data={this.state.dataToDownload}
            filename="data.csv"
            className="hidden"
            ref={(r) => (this.csvLink = r)}
            target="_blank"
          />

      </div>
      <button class="button_log_out" onClick={()=>logout()}>Log out</button>
      <div>
        <input onChange={this.amountHandler} value={this.state.amount} placeholder="Amount spent:" id="amount" style={{position: "fixed", top: "30px", left:"25px", width: "250px", height: "40px", fontSize: "18pt"}}/>
        <input onChange={this.productHandler} value={this.state.product} placeholder="Purchased product:" id="product" style={{position: "fixed", top: "30px", left:"300px", width: "250px", height: "40px", fontSize: "18pt"}}/>
        <button className="button_submit" style={{position: "fixed", top: "30px", left: "800px"}} onClick={() => this.submitWaste()}>Submit</button>
      </div>
      <div>
        <input onChange={this.new_categoryHandler} value={this.state.new_category} placeholder="Enter new category:" style={{position: "fixed", top: "230px", left:"25px", width: "300px", height: "40px", fontSize: "18pt"}}/>
        <button className="button_submit" style={{position: "fixed", top: "230px", left: "350px"}} onClick={() => add_category(this.state.new_category)}>Submit</button>
      </div>
      <div style={{backgroundColor: "#FFF", borderRadius: "50px", padding: "5px", maxWidth: "60%", position: "fixed", top: "600px", left: "25px"}}>
        <h1>{forecast([this.state.chart_month.datasets[0].data[0]], 30)}</h1>
      </div>
    </div>
  );
  }
}

export default App;